import os
import sys
import time

from bcc import BPF

from GlobaLogger import Log
from Main_Test_Util import generate_test_database, generate_random_database
from python_part.BPFBackend import BPFBackend
from python_part.BPFMapLoader import BPFMapLoader
from python_part.PolicyStoreModule import PolicyStoreModule
from python_part.policy_receive.line_solver.comment_solver import CommentSolver
from python_part.policy_receive.line_solver.link_solver import LinkSolver
from python_part.policy_receive.line_solver.set_solver import SetSolver
from python_part.policy_receive.policy_receive_module import PolicyReceiveModule


log = Log(__name__).getlog()


def start_access_control(policy_store_module):

    b = BPF(src_file="main_eBPF.c")
    b.attach_tracepoint(tp="raw_syscalls:sys_enter", fn_name="trace_sys_enter")

    bfp_map_loader = BPFMapLoader()
    all_pplicy = policy_store_module.get_all_policy()
    bfp_map_loader.load_all_policy_to_bpf_map(b, all_pplicy)
    print("开干!")

    bpf_backend = BPFBackend(b,
                             policy_store_module.get_all_policy,
                             policy_store_module.update_entity_path_to_rwclass_id,
                             policy_store_module.update_rwclass_id_to_rwclass,
                             policy_store_module.delete_entity_path_to_rwclass_id,
                             policy_store_module.delete_rwclass_id_to_rwclass)
    try:
        while 1:
            bpf_backend.handle_all_form_ebpf()

            (task, pid, cpu, flags, ts, msg) = b.trace_fields()
            log.info(f"task:{task} pid:{pid} cpu:{cpu} flags:{flags} msg: {msg.decode()}")
            # time.sleep(0.5)
    except KeyboardInterrupt:
        sys.exit()





def set_database_by_policy_file(policy_store_module: PolicyStoreModule, policy_file_path:str):
    line_solver_list = [CommentSolver, LinkSolver, SetSolver]
    line_solver_list = [i(policy_store_module.get_all_policy,
                          policy_store_module.update_entity_path_to_rwclass_id,
                          policy_store_module.update_rwclass_id_to_rwclass,
                          policy_store_module.delete_entity_path_to_rwclass_id,
                          policy_store_module.delete_rwclass_id_to_rwclass) for i in line_solver_list]
    PolicyReceiveModule(tuple(line_solver_list)).accept_policy(policy_file_path)


def set_test_database(policy_store_module):
    tmp = generate_test_database()
    # tmp = generate_random_database()
    policy_store_module.init_database(tmp[0], tmp[1], tmp[2])


def set_random_database(policy_store_module):
    tmp = generate_random_database()
    policy_store_module.init_database(tmp[0], tmp[1], tmp[2])
